package org.mat.ipaas.ucenter.service.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.service.api.system.SysCheckRuleRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysCheckRuleDTO;
import org.mat.ipaas.ucenter.service.modules.MatController;
import org.mat.ipaas.ucenter.service.modules.aop.AutoLog;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysCheckRule;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysCheckRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 编码校验规则
 */
@Slf4j
@Api(tags = "编码校验规则")
@RestController
@RequestMapping("/sys/checkRule")
public class SysCheckRuleController extends MatController<SysCheckRule, ISysCheckRuleService> implements SysCheckRuleRestAPI {

    @Autowired
    private ISysCheckRuleService sysCheckRuleService;

    /**
     * 分页列表查询
     *
     * @param sysCheckRuleDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "编码校验规则-分页列表查询")
    @ApiOperation(value = "编码校验规则-分页列表查询", notes = "编码校验规则-分页列表查询")
    @GetMapping(value = "/list")
    public MatApiResponse queryPageList(
            @SpringQueryMap SysCheckRuleDTO sysCheckRuleDTO,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysCheckRule sysCheckRule = toSysCheckRule(sysCheckRuleDTO);

        QueryWrapper<SysCheckRule> queryWrapper = QueryGenerator.initQueryWrapper(sysCheckRule, request.getParameterMap());
        Page<SysCheckRule> page = new Page<>(pageNo, pageSize);
        IPage<SysCheckRule> pageList = sysCheckRuleService.page(page, queryWrapper);
        return MatApiResponse.success(toSysCheckRuleDTOPage(pageList));
    }


    /**
     * 通过id查询
     *
     * @param ruleCode
     * @return
     */
    @AutoLog(value = "编码校验规则-通过Code校验传入的值")
    @ApiOperation(value = "编码校验规则-通过Code校验传入的值", notes = "编码校验规则-通过Code校验传入的值")
    @GetMapping(value = "/checkByCode")
    public MatApiResponse checkByCode(
            @RequestParam(name = "ruleCode") String ruleCode,
            @RequestParam(name = "value") String value
    ) throws UnsupportedEncodingException {
        SysCheckRule sysCheckRule = sysCheckRuleService.getByCode(ruleCode);
        if (sysCheckRule == null) {
            return MatApiResponse.fail("该编码不存在");
        }
        JSONObject errorResult = sysCheckRuleService.checkValue(sysCheckRule, URLDecoder.decode(value, "UTF-8"));
        if (errorResult == null) {
            return MatApiResponse.success();
        } else {
            MatApiResponse<Object> r = MatApiResponse.fail(errorResult.getString("message"));
            r.setData(errorResult);
            return r;
        }
    }

    /**
     * 添加
     *
     * @param sysCheckRuleDTO
     * @return
     */
    @AutoLog(value = "编码校验规则-添加")
    @ApiOperation(value = "编码校验规则-添加", notes = "编码校验规则-添加")
    @PostMapping(value = "/add")
    public MatApiResponse add(@RequestBody SysCheckRuleDTO sysCheckRuleDTO) {
        SysCheckRule sysCheckRule = toSysCheckRule(sysCheckRuleDTO);
        sysCheckRuleService.save(sysCheckRule);
        return MatApiResponse.success("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysCheckRuleDTO
     * @return
     */
    @AutoLog(value = "编码校验规则-编辑")
    @ApiOperation(value = "编码校验规则-编辑", notes = "编码校验规则-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse edit(@RequestBody SysCheckRuleDTO sysCheckRuleDTO) {
        SysCheckRule sysCheckRule = toSysCheckRule(sysCheckRuleDTO);
        sysCheckRuleService.updateById(sysCheckRule);
        return MatApiResponse.success("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "编码校验规则-通过id删除")
    @ApiOperation(value = "编码校验规则-通过id删除", notes = "编码校验规则-通过id删除")
    @DeleteMapping(value = "/delete")
    public MatApiResponse delete(@RequestParam(name = "id", required = true) String id) {
        sysCheckRuleService.removeById(id);
        return MatApiResponse.success("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "编码校验规则-批量删除")
    @ApiOperation(value = "编码校验规则-批量删除", notes = "编码校验规则-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public MatApiResponse deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysCheckRuleService.removeByIds(Arrays.asList(ids.split(",")));
        return MatApiResponse.success("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "编码校验规则-通过id查询")
    @ApiOperation(value = "编码校验规则-通过id查询", notes = "编码校验规则-通过id查询")
    @GetMapping(value = "/queryById")
    public MatApiResponse queryById(@RequestParam(name = "id", required = true) String id) {
        SysCheckRule sysCheckRule = sysCheckRuleService.getById(id);
        return MatApiResponse.success(toSysCheckRuleDTO(sysCheckRule));
    }

    /**
     * 导出excel
     *
     * @param sysCheckRuleDTO
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysCheckRuleDTO sysCheckRuleDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysCheckRule sysCheckRule = toSysCheckRule(sysCheckRuleDTO);
        return super.exportXls(request, sysCheckRule, SysCheckRule.class, "编码校验规则");
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public MatApiResponse importExcel() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        return super.importExcel(request, response, SysCheckRule.class);
    }


    private Page<SysCheckRuleDTO> toSysCheckRuleDTOPage(IPage<SysCheckRule> pageList) {
        Page<SysCheckRuleDTO> sysCheckRuleDTOPage = new Page<>();
        List<SysCheckRuleDTO> sysCheckRuleDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysCheckRule sysCheckRule : pageList.getRecords()) {
                sysCheckRuleDTOList.add(toSysCheckRuleDTO(sysCheckRule));
            }
        }

        sysCheckRuleDTOPage.setTotal(pageList.getTotal());
        sysCheckRuleDTOPage.setSize(pageList.getSize());
        sysCheckRuleDTOPage.setCurrent(pageList.getCurrent());
        sysCheckRuleDTOPage.setRecords(sysCheckRuleDTOList);

        return sysCheckRuleDTOPage;
    }

    private SysCheckRuleDTO toSysCheckRuleDTO(SysCheckRule sysCheckRule) {
        if (sysCheckRule == null) {
            return null;
        }
        SysCheckRuleDTO sysCheckRuleDTO = new SysCheckRuleDTO();
        sysCheckRuleDTO.setId(sysCheckRule.getId());
        sysCheckRuleDTO.setRuleName(sysCheckRule.getRuleName());
        sysCheckRuleDTO.setRuleCode(sysCheckRule.getRuleCode());
        sysCheckRuleDTO.setRuleJson(sysCheckRule.getRuleJson());
        sysCheckRuleDTO.setRuleDescription(sysCheckRule.getRuleDescription());
        sysCheckRuleDTO.setUpdateBy(sysCheckRule.getUpdateBy());
        sysCheckRuleDTO.setUpdateTime(sysCheckRule.getUpdateTime());
        sysCheckRuleDTO.setCreateBy(sysCheckRule.getCreateBy());
        sysCheckRuleDTO.setCreateTime(sysCheckRule.getCreateTime());
        return sysCheckRuleDTO;
    }

    private SysCheckRule toSysCheckRule(SysCheckRuleDTO sysCheckRuleDTO) {
        if (sysCheckRuleDTO == null) {
            return null;
        }
        SysCheckRule sysCheckRule = new SysCheckRule();
        sysCheckRule.setId(sysCheckRuleDTO.getId());
        sysCheckRule.setRuleName(sysCheckRuleDTO.getRuleName());
        sysCheckRule.setRuleCode(sysCheckRuleDTO.getRuleCode());
        sysCheckRule.setRuleJson(sysCheckRuleDTO.getRuleJson());
        sysCheckRule.setRuleDescription(sysCheckRuleDTO.getRuleDescription());
        sysCheckRule.setUpdateBy(sysCheckRuleDTO.getUpdateBy());
        sysCheckRule.setUpdateTime(sysCheckRuleDTO.getUpdateTime());
        sysCheckRule.setCreateBy(sysCheckRuleDTO.getCreateBy());
        sysCheckRule.setCreateTime(sysCheckRuleDTO.getCreateTime());
        return sysCheckRule;
    }

}
